package cn.kimmking.research.qedis.core.opr;

import cn.kimmking.research.qedis.core.AbstractOperator;

import java.util.Arrays;
import java.util.Objects;

/**
 * common operators.
 *
 * @Author : kimmking(kimmking@apache.org)
 * @create 2024/6/11 下午8:04
 */
public class CommonOperator extends AbstractOperator {

    public int exists(String...keys) {
        return keys == null ? 0 : (int) Arrays.stream(keys).map(getMap()::containsKey)
                .filter(x -> x).count();
    }
    public int del(String...keys) {
        return keys == null ? 0 : (int) Arrays.stream(keys).map(getMap()::remove)
                .filter(Objects::nonNull).count();
    }

    public boolean expire(String key, long ttl) {
        CacheEntry<?> entry = getEntry(key);
        if (entry == null) return false;
        entry.setTtl(ttl * 1000L);
        entry.setTs(System.currentTimeMillis());
        return true;
    }

    public long ttl(String key) {
        CacheEntry<?> entry = getEntry(key);
        if (entry == null) return -2;
        if (entry.getTtl() == -1000L) return -1;
        long ret = (entry.getTs()+entry.getTtl() - CURRENT)/1000;
        if(ret > 0) return ret;
        return -1;
    }


}
